package com.zhanglifan.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhanglifan.domain.*;
import com.zhanglifan.service.ExportService;
import com.zhanglifan.util.UtilFuns;
import com.zhanglifan.webservice.IEpService;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Information
 * Author: ZhangLifan
 * Time: 2017/10/6 8:50
 * Description: ContractServiceImpl
 */
public class ExportServiceImpl extends BaseServiceImpl<Export> implements ExportService {
    private IEpService epService;

    public void setEpService(IEpService epService) {
        this.epService = epService;
    }

    @Override
    public void exportE(String ids){
        try {

/*
* {exportId:'454534',inputDate:'2016-12-12',shipmentPort:'beijing',destinationPort:'shanghai',transportMode:'ship',
* priceCondition:'L/C',boxNums:'3',grossWeights:'200',measurements:'500'"
,products:[{exportProductId:'ep001',factoryId:'111',productNo:'222',packingUnit:'333',cnumber:'444',
boxNum:'555',grossWeight:'666',netWeight:'777',sizeLength:'888',sizeWidth:'999',sizeHeight:'1000',exPrice:'1001',price:'1002',tax:'1003'}]"+"}
*
* */
            String[] idss = ids.split(", ");
            for (String id : idss) {
                Map map = new HashMap();
                Export export = (Export) baseDao.get(Export.class, id);
                map.put("exportId",export.getId());
                map.put("inputDate",UtilFuns.dateTimeFormat(export.getInputDate(),"yyyy-MM-dd"));
                map.put("shipmentPort",export.getShipmentPort());
                map.put("destinationPort",export.getDestinationPort());
                map.put("transportMode",export.getTransportMode());
                map.put("priceCondition",export.getPriceCondition());
                map.put("boxNums",String.valueOf(export.getBoxNums()));
                map.put("grossWeights",String.valueOf(export.getGrossWeights()));
                map.put("measurements",String.valueOf(export.getMeasurements()));

                Set<ExportProduct> eps = export.getExportProducts();

                Set set = new HashSet();
                for (ExportProduct ep : eps) {
                    ExportProduct exportProduct = (ExportProduct) baseDao.get(ExportProduct.class, ep.getId());
                    Map<String,String> mapPro = new HashMap<>();
                    mapPro.put("exportProductId",exportProduct.getId());
                    mapPro.put("factoryId",exportProduct.getFactory().getId());
                    mapPro.put("productNo",exportProduct.getProductNo());
                    mapPro.put("packingUnit",exportProduct.getPackingUnit());
                    mapPro.put("cnumber",String.valueOf(exportProduct.getCnumber()));
                    mapPro.put("boxNum",String.valueOf(exportProduct.getBoxNum()));
                    mapPro.put("grossWeight",String.valueOf(exportProduct.getGrossWeight()));
                    mapPro.put("netWeight",String.valueOf(exportProduct.getNetWeight()));
                    mapPro.put("sizeLength",String.valueOf(exportProduct.getSizeLength()));
                    mapPro.put("sizeWidth",String.valueOf(exportProduct.getSizeWidth()));
                    mapPro.put("sizeHeight",String.valueOf(exportProduct.getSizeHeight()));
                    mapPro.put("exPrice",String.valueOf(exportProduct.getExPrice()));
                    mapPro.put("price",String.valueOf(exportProduct.getPrice()));
                    mapPro.put("tax",String.valueOf(exportProduct.getTax()));
                    set.add(mapPro);
                }
                map.put("products",set);
                String jsonString = JSON.toJSONString(map);

                String result = epService.exportE(jsonString);

                System.out.println("*** result 的值是: " + result + " ***");


                /*
                * {
                      "exportId": "402828fe5efbe301015efbe3f9290000",
                      "state": "2",
                      "remark": "申报成功",
                      "products": [
                        {
                          "exportProductId": "402828fe5efbe301015efbe3f92e0001",
                          "tax": "10.4"
                        }
                      ]
                    }*/
                Map resultMap = JSON.parseObject(result);

                Export e = (Export) baseDao.get(Export.class, (String) resultMap.get("exportId"));
                e.setState(Integer.parseInt((String) resultMap.get("state")));
                e.setRemark((String) resultMap.get("remark"));
                Collection<Map> products = (Collection) resultMap.get("products");
                for (Map m : products) {
                    ExportProduct exportProduct = (ExportProduct) baseDao.get(ExportProduct.class, (String) m.get("exportProductId"));
                    exportProduct.setTax(Double.parseDouble((String) m.get("tax")));
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveOrUpdate(Export entity)  {

        if(UtilFuns.isEmpty(entity.getId())){
            String[] ids = entity.getContractIds().split(", ");
            entity.setState(0);
            entity.setInputDate(new Date());

            StringBuilder sb = new StringBuilder();


            for (String id : ids) {

                Contract contract = (Contract) baseDao.get(Contract.class, id);
                contract.setState(2);
                sb.append(id).append(" ");

                List<ContractProduct> cpList = baseDao.find("from ContractProduct where contract.id=?", ContractProduct.class, new String[]{id});
                for (ContractProduct cp : cpList) {
                    ExportProduct ep = new ExportProduct();
                    try {
                        BeanUtils.copyProperties(ep,cp);
                        ep.setId(null);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    entity.getExportProducts().add(ep);
                    ep.setExport(entity);

                    Set<ExtCproduct> ecList = cp.getExtCproducts();
                    for (ExtCproduct ec: ecList) {
                        ExtEproduct ee = new ExtEproduct();
                        org.springframework.beans.BeanUtils.copyProperties(ec,ee);
                        ee.setId(null);
                        ep.getExtEproducts().add(ee);
                        ee.setExportProduct(ep);
                    }
                }

            }
            entity.setCustomerContract(sb.toString());
        }
        super.saveOrUpdate(entity);
    }
}
